package cn.itcast.reggie.controller;

import cn.itcast.reggie.common.R;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${savepath}")
    private String savepath;

    @PostMapping("/upload")
    public R upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename(); //a.jpg
        //生成一个uuid作为保存文件名称
        String newFileName = UUID.randomUUID().toString().replace("-", "");
        String extName = FilenameUtils.getExtension(originalFilename);
        String saveFileName = newFileName + "." + extName;
        file.transferTo(new File(savepath + saveFileName));
        return R.success( saveFileName);
    }

    @GetMapping("/download")
    public R download(String name, HttpServletResponse response) throws IOException {
        //1.获取下载文件输入流
        FileInputStream fis = new FileInputStream(savepath + name);
        //2.获取直接响应流
        ServletOutputStream outputStream = response.getOutputStream();
        //3.从输入流从读取数据，通过输入流写到客户端
        IOUtils.copy(fis,outputStream);
        return R.success("下载成功");
    }
}
